﻿#region Using

using System;

#endregion

namespace GameLogic.Internal
{

    #region Using

    #endregion

    internal class ProgressTimer
    {
        private float millisecondsDone;

        private float millisecondsGoal;

        internal ProgressTimer()
        {
            this.millisecondsDone = 0;
            this.millisecondsGoal = 1;
            this.Enabled = false;
        }

        internal bool Enabled { get; private set; }

        internal float Progress
        {
            get
            {
                return this.CalculateProgress();
            }
        }

        internal void Update(GameTime gameTime)
        {
            this.millisecondsDone += gameTime.Elapsed.Milliseconds;
            if (this.millisecondsDone >= this.millisecondsGoal)
            {
                this.Enabled = false;
                this.OnElapsed();
            }
        }

        internal event ElapsedDelegate Elapsed;

        internal void Reset()
        {
            this.millisecondsDone = 0;
        }

        internal void Start(float seconds)
        {
            this.millisecondsDone = 0;
            this.millisecondsGoal = seconds * 1000;
            this.Enabled = true;
        }

        internal void Stop()
        {
            this.Enabled = false;
        }

        private float CalculateProgress()
        {
            var progress = this.millisecondsDone / this.millisecondsGoal;

            return progress >= 1 ? 1 : progress;
        }

        private void OnElapsed()
        {
            if (this.Elapsed != null)
            {
                this.Elapsed(this);
            }
            else
            {
                throw new Exception("Kein Abonent für diesen ProgressTimer!");
            }
        }

        internal delegate void ElapsedDelegate(ProgressTimer source);
    }
}